package com.ikingtech.datav.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.datav.enums.FilterTypeEnum;
import com.ikingtech.datav.exception.TemplateExceptionInfo;
import com.ikingtech.datav.mapper.TemplateMapper;
import com.ikingtech.datav.model.entity.*;
import com.ikingtech.datav.model.request.TemplateDTO;
import com.ikingtech.datav.model.request.TemplatePublishDTO;
import com.ikingtech.datav.model.request.TemplateSearchDTO;
import com.ikingtech.datav.model.result.TemplateVO;
import com.ikingtech.framework.sdk.base.model.PageResult;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.utils.Tools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author fucb
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateService extends ServiceImpl<TemplateMapper, TemplateDO> {

    private final TemplateComponentService templateComponentService;

    private final ComponentService componentService;

    private final FilterService filterService;

    public PageResult<TemplateDO> selectByPage(TemplateSearchDTO queryParam) {
        return PageResult.build(this.page(new Page<>(queryParam.getPage(), queryParam.getRows()), Wrappers.<TemplateDO>lambdaQuery()
                .like(Tools.Str.isNotBlank(queryParam.getName()), TemplateDO::getName, queryParam.getName())
                .eq(Tools.Str.isNotBlank(queryParam.getId()), TemplateDO::getId, queryParam.getId())
                .eq(Tools.Str.isNotBlank(queryParam.getUserId()), TemplateDO::getUserId, queryParam.getUserId())
                .eq(Objects.nonNull(queryParam.getIsSystem()), TemplateDO::getIsSystem, queryParam.getIsSystem())));
    }

    public TemplateVO getInfo(String id) {
        TemplateDO entity = this.baseMapper.selectById(id);
        if (null == entity) {
            throw new FrameworkException(TemplateExceptionInfo.TEMPLATE_NOT_FOUND);
        }
        return BeanUtil.copyProperties(entity, TemplateVO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(TemplateDTO param) {
        TemplateDO template = BeanUtil.copyProperties(param, TemplateDO.class);
        template.setId(IdUtil.simpleUUID());
        this.baseMapper.insert(template);
    }

    public void edit(TemplateDTO param) {
        if (!this.exist(param.getId())) {
            throw new FrameworkException(TemplateExceptionInfo.TEMPLATE_NOT_FOUND);
        }
        TemplateDO template = BeanUtil.copyProperties(param, TemplateDO.class);
        this.baseMapper.updateById(template);
    }

    public void delete(String id) {
        this.baseMapper.deleteById(id);
    }

    public boolean exist(String id) {
        return this.baseMapper.exists(Wrappers.<TemplateDO>lambdaQuery().eq(TemplateDO::getId, id));
    }

    @Transactional(rollbackFor = Exception.class)
    public void turn(TemplatePublishDTO param, InfoDO byId) {
        String id = param.getScreen().getId();
        TemplateDTO template = param.getTemplate();

        List<ComponentDO> listByScreenId = componentService.getListByScreenId(id);
        List<FilterDO> filterDOList = filterService.getListByScreenId(id);

        TemplateDO templateDO = new TemplateDO();
        String templateId = IdUtil.simpleUUID();
        templateDO.setId(templateId);
        templateDO.setDescription(template.getDescription());
        templateDO.setSnapshot(template.getSnapshot());
        templateDO.setIsSystem(true);
        templateDO.setHeight(template.getHeight());
        templateDO.setWidth(template.getWidth());
        templateDO.setName(template.getName());
        templateDO.setUserId(byId.getCreateBy());
        templateDO.setCreateBy(Me.id());
        Map<String, String> componentNameMap = new HashMap<>(4);
        List<TemplateComponentDO> collect = listByScreenId.stream().map(e -> {
            String v = Tools.Str.removePrefix(e.getName(), "V") + "_" + RandomUtil.randomString(9);
            componentNameMap.put(e.getId(), v);
            TemplateComponentDO templateComponent = BeanUtil.copyProperties(e, TemplateComponentDO.class);
            templateComponent.setId(v);
            templateComponent.setTemplateId(templateId);
            templateComponent.setVersion(1);
            return templateComponent;
        }).collect(Collectors.toList());

        List<HashMap<String, Object>> list = Tools.Json.toBean(byId.getPages(), new TypeReference<>() {
        });
        if (Tools.Coll.isNotBlank(list)) {
            list.forEach(e -> {
                List<String> children = Tools.Json.objToBean(e.get("children"), new TypeReference<>() {
                });
                List<String> vList = children.stream().map(componentNameMap::get).collect(Collectors.toList());
                e.put("children", vList);
            });
        }
        byId.setCreateTime(null);
        byId.setUpdateTime(null);
        byId.setPages(Tools.Json.toJsonStr(list));
        templateDO.setConfig(Tools.Json.toJsonStr(byId));
        this.baseMapper.insert(templateDO);
        templateComponentService.saveBatch(collect);

        //过滤器
        if (!filterDOList.isEmpty()) {
            filterDOList.forEach(e -> {
                e.setScreenId(null);
                e.setId(IdUtil.simpleUUID());
                e.setTemplateId(templateId);
                e.setFilterType(FilterTypeEnum.TEMPLATE.name());
            });
            filterService.saveBatch(filterDOList);
        }
    }
}
